
// app/middleware/gzip.js
// options === app.config.gzip

const isJSON = require('koa-is-json');

// 为 nodejs 内置的组件
// 详细参见: https://nodejs.org/dist/latest-v6.x/docs/api/zlib.html
const zlib = require('zlib');
module.exports = (options,app) => {
    return function* gzip(next) {
        yield next;

        // 后续中间件执行完成后将响应体转换成 gzip
        let body = this.body;
        let encoding = options.encoding || 'utf-8';
        if(!body)return;
        // 支持 options.threshold
        if(options.threshold && this.length < options.threshold)return;
        if(isJSON(body)) body = JSON.stringify(body);
        // 设置 gzip body，修正响应头
        this.body = zlib.createGzip().end(body);
        this.set('Content-Encoding', encoding);

    }
};